package markor.jpa.hello.jpa.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.io.IOException;
import java.util.List;

// @RestControllerAdvice
@Slf4j
public class MyExceptionHandler {
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BindException.class)
    public String hello(HttpServletRequest request, HttpServletResponse response, BindException e) throws IOException {
        String result = "";
        if (e.hasErrors()) {
            List<ObjectError> errors = e.getAllErrors();
            for (ObjectError error: errors) {
                String objectName = error.getObjectName();
                String message = error.getDefaultMessage();
                result+= objectName+":"+message;
                result += String.format("%s:%s\r\n",objectName, message);
            }
        }
        log.error("Param Exception! ", e);
        System.out.println(e.getMessage());
        return result;
    }
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String hello1(HttpServletRequest request, HttpServletResponse response, MethodArgumentNotValidException e) throws IOException {
        String result = "";
        String errorMsg = e.getBindingResult().getFieldErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .findFirst()
                .orElse(e.getMessage());
        System.out.println("***********   1   **************");
        log.error("Param Exception! ", e);
        System.out.println(e.getMessage());
        return errorMsg;
    }
}
